package com.rentcars.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rentcars.entity.Account;
import com.rentcars.mapper.AccountMapper;
import com.rentcars.service.AccountService;
import com.rentcars.utils.DateUtils;
import com.rentcars.utils.Md5Util;
import com.rentcars.utils.UuidUtil;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 类描述：
 *
 * @author 张吉哲
 * @date 2021/3/1 14:06
 */
@Service
public class AccountServiceImpl implements AccountService {

  private final AccountMapper accountMapper;

  public AccountServiceImpl(AccountMapper accountMapper) {
    this.accountMapper = accountMapper;
  }

  @Override
  public PageInfo<Account> selectAllAccount(Account account, Integer curr,
      Integer pageSize) {
    PageHelper.startPage(curr, pageSize);
    List<Account> accounts = accountMapper.selectAllAccount(account);
    return new PageInfo<Account>(accounts);
  }

  @Override
  public Boolean insertAccount(Account account) {
    account.setAddtime(DateUtils.getDateString(new Date()));
    account.setUid(UuidUtil.getUuid());
    account.setPwdsalt(UuidUtil.getUuid());
    account.setUserpwd(Md5Util.md5(account.getUserpwd() + account.getPwdsalt()));
    return accountMapper.insertSelective(account) > 0;
  }

  @Override
  @Transactional
  public Boolean deleteAccountsByUids(String[] checkUid) {
    Integer result = accountMapper.deleteByPrimaryKeys(checkUid);
    if (result == null || checkUid.length != result) {
      throw new RuntimeException("结束");
    } else {
      return true;
    }
  }

  @Override
  public Account selectAccountByPrimaryKey(String uid) {
    return accountMapper.selectByPrimaryKey(uid);
  }

  @Override
  public Boolean updateAccountByPrimaryKey(Account account) {
    account.setEdittime(DateUtils.getDateString(new Date()));
    int result = accountMapper.updateByPrimaryKey(account);
    return result > 0;
  }

  @Override
  public Boolean selectAccountByUsername(String username, String uid) {
    Account account = accountMapper.selectAccountByUsername(username);
    if (account != null) {
      return account.getUid().equals(uid);
    }
    return true;
  }

  @Override
  public Boolean deleteAccountsByUid(String uid) {
    Integer result = accountMapper.updateByAccountId(uid);
    return result == 1;
  }

  @Override
  public Boolean updateAccountStateByUid(String uid, Integer userstate) {
    return accountMapper.updateStateAccount(uid, userstate) == 1;
  }

  @Override
  public Account selectAccountRole(String username) {
    return accountMapper.selectAccountRole(username);
  }

  @Override
  public String selectPwdSaltByUsername(String username) {
    return accountMapper.selectPwdSaltByUsername(username);
  }
}
